package LC;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

/**
 * https://leetcode.com/problems/3sum/description/
 * Given an array S of n integers,
 * are there elements a, b, c in S such that a + b + c = 0?
 * Find all unique triplets in the array which gives the sum of zero.
 * Note: The solution set must not contain duplicate triplets.
 * For example, given array S = [-1, 0, 1, 2, -1, -4],
 * A solution set is:
 * [
 * [-1, 0, 1],
 * [-1, -1, 2]
 * ]
 */
public class LC_015_3Sum_Loop_TwoPointers {
    public static void main(String[] args) {
//        Scanner sc = new Scanner(System.in);
//        while (sc.hasNext()) {
//            String[] arr = sc.nextLine().trim().split("\\s+");
//            int[] a = new int[arr.length];
//            for (int i = 0; i < a.length; i++) {
//                a[i] = Integer.parseInt(arr[i]);
//            }
//            System.out.println(threeSum(a));
//        }
//        sc.close();

        // int[] a = { -1, 0, 1, -5, 1, 4, 6 };
        int[] a = {-2, 0, 1, 1, 2};
        List<List<Integer>> res = threeSum(a);
        System.out.println(res.toString());
    }

    private static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ansList = new ArrayList<>();
        if (nums.length < 3) return ansList;
        Arrays.sort(nums);

        for (int i = 0; i < nums.length - 2; i++) {
            if (i == 0 || nums[i - 1] < nums[i]) {
                //开始搜索
                int st = i + 1;
                int en = nums.length - 1;
                //快排的思想
                while (st < en) {
                    int sum = nums[i] + nums[st] + nums[en];
                    if (sum == 0) {
                        ansList.add(Arrays.asList(nums[i], nums[st], nums[en]));
                        st++;
                        en--;
                        while (st < en && nums[st] == nums[st - 1])
                            st++;
                        while (st < en && nums[en] == nums[en + 1])
                            en--;
                    } else if (sum > 0)
                        en--;
                    else
                        st++;
                }
                //结束搜索
            }
        }

        return ansList;
    }
}